import { JavascriptGenerator, javascriptGenerator } from "blockly/javascript";
import { Tanslate } from "./translate";
import * as Blockly from 'blockly/core';
import { getValue } from "./com";
export namespace Dog {
    const blocks = [
        {
            "key": "net_request",
            "message0": "%{use} %1 %{from} %2 %{net_request} %{net_request_and} %{net_request_with} %3 %{net_request_and} %{return} %4",
            "args0": [
                {
                    "type": "field_dropdown",
                    "name": "method",
                    "options": [
                        ["GET", "GET"],
                        ["POST", "POST"],
                        ["PUT", "PUT"],
                        ["DELETE", "DELETE"]
                    ]
                },
                {
                    "type": "input_value",
                    "name": "url",
                    "check": "String"
                },
                {
                    "type": "input_value",
                    "name": "body",
                    "check": "String"
                },
                {
                    "type": "field_dropdown",
                    "name": "responseType",
                    "options": [
                        ["%{string}", "string"],
                        ["Blob", "blob"],
                        ["%{json}", "json"],
                        ["%{byte}", "arraybuffer"],
                    ]
                },
            ],
            "output": "Promise",
            "inputsInline": true,
            "nextStatement": null,
            "previousStatement": null,
            "tooltip": "%{net_request_tips}",
            "colour": 360
        },
        {
            "key": "net_request_result",
            "message0": "%{from} %1 %{get} %2",
            "args0": [
                {
                    "type": "input_value",
                    "name": "result",
                    "check": "Object"
                },
                {
                    "type": "field_dropdown",
                    "name": "key",
                    "options": [
                        ["%{net_request_result_readyState}", "readyState"],
                        ["%{net_request_result_status}", "status"],
                        ["%{net_request_result_statusText}", "statusText"],
                        ["%{net_request_result_content}", "content"],
                        ["%{net_request_result_responseText}", "responseText"],
                    ]
                },
            ],
            "output": ["String", "Number","arraybuffer","blob"],
            "colour": 360
        },
        {
            "key": "hex_to_rgb",
            "message0": "%{hex_to_rgb} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "value"
                },
            ],
            "nextStatement": null,
            "previousStatement": null,
            "output": "Object",
            "inputsInline": true,
            "colour": 360
        },
        {
            "key": "parse_rgb",
            "message0": "%{parse_rgb} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "value"
                },
            ],
            "nextStatement": null,
            "previousStatement": null,
            "output": "Object",
            "inputsInline": true,
            "colour": 360
        },
        {
            "key": "download",
            "message0": "%{from} %1 %{download}%{element_src} %{net_request_and} %{set} %{resource_name} %2",
            "args0": [
                {
                    "type": "input_value",
                    "name": "url"
                },
                {
                    "type": "input_value",
                    "name": "fileName"
                },
            ],
            "nextStatement": null,
            "previousStatement": null,
            "inputsInline": true,
            "colour": 360
        },
        {
            "key": "download_all",
            "message0": "%{from} %1 %{download_all}%{element_src}",
            "args0": [
                {
                    "type": "input_value",
                    "name": "resources"
                }
            ],
            "nextStatement": null,
            "previousStatement": null,
            "inputsInline": true,
            "colour": 360
        },
        {
            "key": "create_resource",
            "message0": "%{create_resource} \n %{resource_name} %1 %{element_href} %2 %{type} %3",
            "args0": [
                {
                    "type": "input_value",
                    "name": "name",
                    "check": "String"
                },
                {
                    "type": "input_value",
                    "name": "url",
                    "check": "String"
                },
                {
                    "type": "field_dropdown",
                    "name": "type",
                    "options": [
                        ["%{image}", "image"],
                        ["%{canvas}", "canvas"],
                        ["%{media}", "media"],
                        ["%{stylesheet}", "stylesheet"],
                        ["%{other}", "other"],
                        ["%{script}", "script"],
                    ]
                },
            ],
            "output": "Object",
            "inputsInline": true,
            "colour": 360
        },
        {
            "key": "find_resources",
            "message0": "%{from} %{page} %{find_resources} %1",
            "args0": [
                {
                    "type": "field_dropdown",
                    "name": "type",
                    "options": [
                        ["%{image}", "image"],
                        ["%{canvas}", "canvas"],
                        ["%{media}", "media"],
                        ["%{stylesheet}", "stylesheet"],
                        ["%{other}", "other"],
                        ["%{script}", "script"],
                    ]
                },
            ],
            "output": "Promise",
            "inputsInline": true,
            "colour": 360
        },
        {
            "key": "dog_set_cache",
            "message0": "%{set_cache} \n %{key} %1 %{value} %2",
            "args0": [
                {
                    "type": "input_value",
                    "name": "key",
                    "check": "String"
                },
                {
                    "type": "input_value",
                    "name": "value",
                }
            ],
            "output": "Promise",
            "nextStatement": null,
            "previousStatement": null,
            "colour": 360
        },
        {
            "key": "dog_get_cache",
            "message0": "%{get_cache} %{key} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "key",
                    "check": "String"
                }
            ],
            "output": "Promise",
            "colour": 360
        },
        {
            "key": "dog_clear_cache",
            "message0": "%{clear_cache} %{key} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "key",
                    "check": "String"
                }
            ],
            "output": "Promise",
            "nextStatement": null,
            "previousStatement": null,
            "colour": 360
        },
        {
            "key": "get_template",
            "message0": "%{get_template} %1 %{net_request_and} %{net_request_with} %2",
            "args0": [
                {
                    "type": "field_input",
                    "name": "key",
                }, {
                    "type": "input_value",
                    "name": "args",
                    "check": "Object"
                }
            ],
            "output": "String",
            "colour": 360
        },
        {
            "key": "dog_get_resource",
            "message0": "%{get_resource} %{key} %1 %2",
            "args0": [
                {
                    "type": "input_value",
                    "name": "key",
                    "check": "String"
                },
                {
                    "type": "field_dropdown",
                    "name": "type",
                    "options": [
                        ["%{resource_url}", "url"],
                        ["%{resource_text}", "text"],
                    ]
                },
            ],
            "output": "Promise",
            "colour": 360
        },
        {
            "key": "open_file",
            "message0": "%1",
            "args0": [
                {
                    "type": "field_dropdown",
                    "name": "type",
                    "options": [
                        ["%{open_file}", "false"],
                        ["%{open_file_text}", "true"],
                    ]
                },
            ],
            "output": "Promise",
            "colour": 360
        },
        {
            "key": "load_image",
            "message0": "%{from} %1 %{load_image}",
            "args0": [
                {
                    "type": "input_value",
                    "name": "url",
                    "check": "String"
                }
            ],
            "output": "Promise",
            "tooltip": "%{load_image_tips}",
            "colour": 360
        },
        {
            "key": "read_file",
            "message0": "%{from} %1 %{read} %{to} %2",
            "args0": [
                {
                    "type": "input_value",
                    "name": "VALUE",
                    "check": "File"
                },
                {
                    'type': 'field_dropdown',
                    'name': 'TYPE',
                    'options': [
                        ['%{text}', 'text'],
                        ['base64', 'base64'],
                        ['%{arraybuffer}', 'arraybuffer']
                    ],
                },
            ],
            "output": "Promise",
            "inputsInline": true,
            "tooltip": "%{read_file_tips}",
            "colour": 360
        },
        {
            "key": "create_notification",
            "message0": "%{create_notification}( %{title}: %1 %{content}: %2 )",
            "args0": [
                {
                    "type": "input_value",
                    "name": "title",
                    "check": "String"
                },
                {
                    "type": "input_value",
                    "name": "content",
                    "check": "String"
                }
            ],
            "output": "Promise",
            "nextStatement": null,
            "previousStatement": null,
            "tooltip": "%{create_notification_tips}",
            "colour": 360
        },
        // {
        //     "key": "desktop_capture",
        //     "message0": "%{desktop_capture} \n %{desktop_capture_screen} %1 %{desktop_capture_window} %2 %{desktop_capture_tab} %3 %{desktop_capture_audio} %4",
        //     "args0": [
        //         {
        //             "type": "field_checkbox",
        //             "name": "screen",
        //             "checked": true
        //         },
        //         {
        //             "type": "field_checkbox",
        //             "name": "window",
        //             "checked": false
        //         },
        //         {
        //             "type": "field_checkbox",
        //             "name": "tab",
        //             "checked": false
        //         },
        //         {
        //             "type": "field_checkbox",
        //             "name": "audio",
        //             "checked": false
        //         },
        //     ],
        //     "output": "Promise",
        //     "colour": 360
        // }, {
        //     "key": "desktop_capture_result",
        //     "message0": "%{from} %1 %{get} %2",
        //     "args0": [
        //         {
        //             "type": "input_value",
        //             "name": "result",
        //             "check": "Object"
        //         },
        //         {
        //             "type": "field_dropdown",
        //             "name": "key",
        //             "options": [
        //                 ["%{desktop_capture_result_streamId}", "streamId"],
        //                 ["%{desktop_capture_result_requestId}", "desktopMediaRequestId"],
        //             ]
        //         },
        //     ],
        //     "output": ["String", "Number"],
        //     "colour": 360
        // },
        // {
        //     "key": "cancel_desktop_capture",
        //     "message0": "%{cancel_desktop_capture} %1",
        //     "args0": [
        //         {
        //             "type": "input_value",
        //             "name": "args",
        //             "check": "Number"
        //         }
        //     ],
        //     "nextStatement": null,
        //     "previousStatement": null,
        //     "colour": 360
        // },
    ]

    export function init() {
        initGenerator()
        Tanslate.tr(blocks).forEach((item: any) => {
            Blockly.Blocks[item.key] = {
                init: function (this: any) {
                    this.jsonInit(item);
                }
            }
        })
    }

    export function getTools() {
        const netBlocks = {
            kind: 'category',
            name: Blockly.Msg['dog'],
            "colour": 360,
            contents: [] as any[]
        }
        blocks.forEach((item: any) => {
            netBlocks.contents.push({
                kind: 'block',
                type: item.key
            })
        })

        return netBlocks
    }

    function initGenerator() {
        javascriptGenerator.forBlock['net_request'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const method = block.getFieldValue('method')
            const responseType = block.getFieldValue('responseType')
            const url = getValue(block, generator, 'url')?.trim();
            const body = getValue(block, generator, 'body')?.trim();
            if (!url) {
                throw new Error(block.id);
            }
            return `Dog.httpRequest({url:${url},  method: '${method}', body: ${body || undefined},responseType:'${responseType}' })`;
        }

        javascriptGenerator.forBlock['net_request_result'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const result = getValue(block, generator, 'result');
            const key = getValue(block, generator, 'key');
            if (!result || !key) {
                throw new Error(block.id);
            }
            return `${result}.${key}`
        }

        javascriptGenerator.forBlock['hex_to_rgb'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const value = getValue(block, generator, 'value')?.trim();
            if (!value) {
                throw new Error(block.id);
            }
            return `Dog.hexToRgb(${value})`;
        }

        javascriptGenerator.forBlock['parse_rgb'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const value = getValue(block, generator, 'value')?.trim();
            if (!value) {
                throw new Error(block.id);
            }
            return `Dog.parseRgba(${value})`;
        }

        javascriptGenerator.forBlock['download'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const url = getValue(block, generator, 'url')?.trim();
            const fileName = getValue(block, generator, 'fileName')?.trim();
            if (!url) {
                throw new Error(block.id);
            }
            if (block.outputConnection?.targetBlock()) {
                return `Dog.download(${url}, ${fileName || 'undefined'})`;
            }
            return `Dog.download(${url}, ${fileName || 'undefined'});\n`;
        }

        javascriptGenerator.forBlock['download_all'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const resources = getValue(block, generator, 'resources')?.trim();
            if (!resources) {
                throw new Error(block.id);
            }
            if (block.outputConnection?.targetBlock()) {
                return `Dog.downloadAll(${resources})`;
            }
            return `Dog.downloadAll(${resources});\n`;
        }

        javascriptGenerator.forBlock['create_resource'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const name = getValue(block, generator, 'name')
            const url = getValue(block, generator, 'url')
            const type = getValue(block, generator, 'type')
            if (!name || !url || !type) {
                throw new Error(block.id);
            }
            return `{name: ${name}, url: ${url}, type: '${type}'}`;
        }

        javascriptGenerator.forBlock['find_resources'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const type = getValue(block, generator, 'type')
            return `Dog.findResources(${type ? ('"' + type + '"') : 'undefined'})`;
        }

        javascriptGenerator.forBlock['dog_set_cache'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const key = getValue(block, generator, 'key');
            const value = getValue(block, generator, 'value');
            if (!key || value === undefined) {
                throw new Error(block.id);
            }
            return `Dog.setValue(${key}, ${value});\n`;
        }
        javascriptGenerator.forBlock['dog_get_cache'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const key = getValue(block, generator, 'key');
            if (!key) {
                throw new Error(block.id);
            }
            return `Dog.getValue(${key})`;
        }
        javascriptGenerator.forBlock['dog_clear_cache'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const key = getValue(block, generator, 'key');
            if (!key) {
                throw new Error(block.id);
            }
            return `Dog.deleteValue(${key});\n`;
        }

        javascriptGenerator.forBlock['dog_get_resource'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const key = getValue(block, generator, 'key');
            const type = getValue(block, generator, 'type')
            if (!key) {
                throw new Error(block.id);
            }
            if(type==='text'){
                return `Dog.getResourceText(${key})`;
            }
            return `Dog.getResourceUrl(${key})`;
        }

        javascriptGenerator.forBlock['get_template'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const key = block.getFieldValue('key');
            const args = getValue(block, generator, 'args');
            if (!key) {
                throw new Error(block.id);
            }
            return `get_${key}(${args || '{}'})`
        }

        javascriptGenerator.forBlock['open_file'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const args = getValue(block, generator, 'type');
            return `Dog.openFile(${args})`
        }

        javascriptGenerator.forBlock['load_image'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const url = getValue(block, generator, 'url');
            return `Dog.loadImage(${url})`
        }

        javascriptGenerator.forBlock['read_file'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            const TYPE = getValue(block, generator, 'TYPE')
            if (!VALUE) {
                throw new Error(block.id);
            }
            return `Dog.readFile(${VALUE},"${TYPE}")`;
        }

        javascriptGenerator.forBlock['create_notification'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const title = getValue(block, generator, 'title');
            const content = getValue(block, generator, 'content');
            if (!title || !content) {
                throw new Error(block.id);
            }
            return `Dog.notification(${title}, ${content})`
        }

        javascriptGenerator.forBlock['desktop_capture'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const val1 = getValue(block, generator, 'screen');
            const val2 = getValue(block, generator, 'window');
            const val3 = getValue(block, generator, 'tab');
            const val4 = getValue(block, generator, 'audio');
            const ar: string[] = []
            if (val1 === 'TRUE') {
                ar.push('"screen"')
            }
            if (val2 === 'TRUE') {
                ar.push('"window"')
            }
            if (val3 === 'TRUE') {
                ar.push('"tab"')
            }
            if (val4 === 'TRUE') {
                ar.push('"audio"')
            }
            return `Dog.desktopCapture([${ar.join(',')}] )`
        }

        javascriptGenerator.forBlock['desktop_capture_result'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const result = getValue(block, generator, 'result');
            const key = getValue(block, generator, 'key');
            if (!result || !key) {
                throw new Error(block.id);
            }
            return `${result}.${key}`
        }

        javascriptGenerator.forBlock['cancel_desktop_capture'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const args = getValue(block, generator, 'args');
            if (!args) {
                throw new Error(block.id);
            }
            return `Dog.cancelDesktopCapture(${args});\n`
        }
    }
}